<?php
namespace Index\Controller;
use Think\Controller;
class LoginController extends Controller {
	public function code(){
		$REDIRECT_URI='http://sunwayuchoice.com/index.php/Login/index';
		$scope='snsapi_base'; //静默授权 关注用户默认的权限
		//$scope='snsapi_userinfo'; //用户点击授权  未关注也可以获取
		$url='http://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('APPID').'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
		$recode= file_get_contents($url);

		header("Location:".$url);
	}

	//表单令牌短信验证防止重复提交
	public function check_form(){
    	session("token",md5(rand(10000,99999)));
    	$check=session("token");
    	return $check;
    }
	
    public function index(){
    	$code = $_GET['code'];
    	//P($code);
		define('WX_OAUTH2_CALLBACK','https://api.weixin.qq.com/sns/oauth2/access_token');       
		$token_url = WX_OAUTH2_CALLBACK.'?appid='.C('APPID').'&secret='.C('APPSECRET').'&code='.$code.'&grant_type=authorization_code'; 
		$token = json_decode(file_get_contents($token_url), true);
		$openid = $token['openid'];//输出openid
		
    	$arr=$this->check_form();
    	//print_r($arr);exit;
    	$this->assign('openid',$openid);
    	$this->assign('arr',$arr);
    	$this->display('index');
    }

    //发送短信
    public function msg()
    {   
        $num=$this->randString();
        $phone=trim(I('phone'));

        $list=M('customer')->where('phone="'.$phone.'"')->find();
        if (!empty($list)) {
        	//error('手机号已经被注册',$_SERVER['HTTP_REFERER']);
        	$this->ajaxReturn(array('s'=>'no','m'=>"手机号已经被注册"));
        }


        //表单令牌验证
        $token=I('token');
        if ($token!=session('token') || empty($token)){
		 // 令牌验证错误
		 //exit('令牌验证错误');
		 $this->ajaxReturn(array('s'=>"check",'m'=>"令牌验证错误"));
		}else{
        //正则验证手机号
        if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){  
		  
	        $c=Vendor('Alidayu.top.TopClient'); 
	        $c=new \TopClient();
	        $c->appkey =C('AlidayuAppKey');
	        $c->secretKey =C('AlidayuAppSecret');
	        $req=Vendor('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
	        $req=new \AlibabaAliqinFcSmsNumSendRequest();
	        $req->setSmsType("normal");
	        $req->setSmsFreeSignName("注册验证");
	        $req->setSmsParam("{\"code\":\"$num\",\"product\":\"尚元优家Uchoice\"}");
	        $req->setRecNum($phone);
	        $req->setSmsTemplateCode("SMS_12200894");
	        $resp = $c->execute($req);
			S($phone,$num,120);
			$this->ajaxReturn(array('s'=>'ok','m'=>"发送成功"));
        }else{  
        	$this->ajaxReturn(array('s'=>"fail",'m'=>"令牌验证错误"));
		    //$this->error('手机格式不正确');
		}  
     }
	}
    /**
     * 获取随机位数数字
     * @param  integer $len 长度
     * @return string       
     */
    protected static function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str   = substr($chars, 0, $len);
        return $str;
    }


    //验证短信验证
    public function check(){//exit("qqq");
	        $num=I('num');
	        $phone = I('phone');
	        $verify = S($phone);
	        if (empty($verify)) {
	            //exit('验证码失效');
	            $this->ajaxReturn(array('c'=>"shixiao",'m'=>"验证码失效"));exit();
	        }

	        if ($verify != $num) {
	            //echo '验证失败';
	            $this->ajaxReturn(array('c'=>"error",'m'=>"验证码错误"));exit();
	        }else{
	           $this->ajaxReturn(array('c'=>"yes",'m'=>"验证成功"));exit();
	        }
    }
    //普通用户注册
    public function register(){
        $phone=trim(I('phone'));
       	$openid=I('openid');
    	$plot=trim(I('plot'));
    	$sex=trim(I('sex'));
    	$list=M('customer')->where('openid="'.$openid.'"')->find();
    	if (!empty($list)) {
    		error('您已经是会员了，请进行登录',$_SERVER['HTTP_REFERER']);
    	}

    	//实例化表
    	$customer=M('customer');
    	$data = array(
    		'phone' => $phone, 
    		'openid'=>$openid,
    		'plot' => $plot, 
    		'sex' => $sex, 
    		'ctime'=>time(),
    		'mtime'=>time(),
    		);
    	//print_r($data);exit('@#$');
    	$res_add=$customer->data($data)->add();
    	if (false !== $res_add) {
    		echo '恭喜你成功成为尚元会员';
    	}else{
    		echo '再试一次咯';
    	}

    }


    //管理员注册用户注册
    public function register_(){
        $phone=trim(I('phone'));
       	$openid=I('openid');
    	$plot=trim(I('plot'));
    	$sex=trim(I('sex'));
    	$list=M('customer')->where('openid="'.$openid.'"')->find();
    	if (!empty($list)) {
    		error('您已经是会员了，请进行登录',$_SERVER['HTTP_REFERER']);
    	}

    	//实例化表
    	$customer=M('customer');
    	$data = array(
    		'phone' => $phone, 
    		'openid'=>$openid,
    		'plot' => $plot, 
    		'sex' => $sex, 
    		'ctime'=>time(),
    		'mtime'=>time(),
    		);
    	print_r($data);exit('@#$');
    	$res_add=$customer->data($data)->add();
    	if (false !== $res_add) {
    		echo '恭喜你成功成为尚元会员';
    	}else{
    		echo '再试一次咯';
    	}

    }
}
?>